﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BaseUnits;

namespace Formulas
{
    public class BuildMargin : IBuildMargin
    {
        BaseUnits.IPowerGrid grid;
        public BuildMargin(IPowerGrid grid)
        {
            this.grid = grid;
        }
        public double GetBM(DateTime dateFrom, DateTime dateTo)
        {
            SortedList<DateTime, IPowerUnit> unitList = this.grid.DateSortedPowerUnits();
            double eg = 0; //EGm,y
            double ef = 0; //EFel,m,y
            double buildMargin = 0;
            double totalDispatch = 0;
            double totalEgXEf = 0; // EGm,y X EFel,m,y
            double totalGridDispach = grid.TotalOutgoing(dateFrom, dateTo);
            double gridDispachPercentage = totalGridDispach * 0.2;

            int i = 1;
            foreach (IPowerUnit pu in unitList.Values)
            {
                if ((i <= 5) || (totalDispatch < gridDispachPercentage))
                {
                    eg = pu.TotalOutgoing(dateFrom,dateTo);
                    ef = pu.EmissionFactor(dateFrom);
                    totalEgXEf = eg * ef;
                    totalDispatch = totalDispatch + eg;
                }
                i++;
            }

            



            
            //SortedList<DateTime, IPowerUnit> unitList = this.grid.DateSortedPowerUnits();
            //int i = 1;
            //double totalGridDispach = 0;
            //double gridDispachPercentage = 0;
            //while (dateFrom <= dateTo)
            //{
            //    totalGridDispach = this.grid.TotalOutgoing(dateFrom, dateTo);
            //    gridDispachPercentage = totalGridDispach * 0.2;
            //    totalDispatch = 0;    
            //    i = 1;
            //    foreach (IPowerUnit pu in unitList.Values)
            //    {
            //        //pu.TotalOutgoing(
            //        totalGridDispach = this.grid.GetTotalOutgoing(dateFrom);
            //        gridDispachPercentage = totalGridDispach * 0.2;
            //        if ((i <= 5) || (totalDispatch < gridDispachPercentage))
            //        {
            //            eg = pu.GetOutgoing(dateFrom);
            //            ef = pu.EmissionFactor(dateFrom);
            //            totalEgXEf = eg * ef;
            //            totalDispatch = totalDispatch + eg;
            //        }
            //    }
            //    dateFrom = dateFrom.AddHours(1);
            //}
            buildMargin = totalEgXEf / totalDispatch;
            return buildMargin;
        }

        public double GetMonthBM(int month, int year, BaseUnits.IPowerPlant powerPlant)
        {
            throw new NotImplementedException();
        }
    }
}
